from flask import Blueprint, render_template, flash, redirect, url_for
from flask_login import login_required
from app.models.category import Category
from app.forms.category import CategoryForm

bp = Blueprint('category', __name__)


@bp.before_request
@login_required
def before_request():
    pass


@bp.route('/')
def index():
    model = Category.tree()
    return render_template(
        'admin/category/index.html',
        model=model)


@bp.route('/create', methods=['GET', 'POST'])
def create():
    form = CategoryForm()
    model = Category()
    if model.save(form):
        flash('成功创建栏目{}'.format(model.title), 'success')
        return redirect(url_for('category.index'))
    return render_template('admin/category/create.html', form=form)


@bp.route('/update/<int:id>', methods=['GET', 'POST'])
def update(id):
    form = CategoryForm()
    model = Category.query.get_or_404(id)
    if model.save(form):
        flash('修改成功', 'success')
        return redirect(url_for('category.index'))

    form.load(model)
    return render_template('admin/category/update.html', form=form)


@bp.route('/delete/<int:id>')
def delete(id):
    model = Category.query.get_or_404(id)
    if model.articles:
        flash('栏目下面有文章，请先删除文章后再来删除', 'warning')
        return redirect(url_for('category.index'))
    model.delete(True)
    flash('删除成功', 'success')
    return redirect(url_for('category.index'))
